package com.bzkj.web.controller.system;

import com.bzkj.common.annotation.LogC;
import com.bzkj.common.core.controller.BaseController;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.entity.SysDept;
import com.bzkj.common.core.domain.entity.SysRole;
import com.bzkj.common.core.domain.entity.SysUser;
import com.bzkj.common.core.domain.model.LoginUser;
import com.bzkj.common.core.page.TableDataInfo;
import com.bzkj.common.enums.BusinessType;
import com.bzkj.common.utils.StringUtils;
import com.bzkj.common.utils.poi.CsvExportUtils;
import com.bzkj.common.utils.poi.ExcelPDFUtil;
import com.bzkj.common.utils.poi.ExcelUtil;
import com.bzkj.framework.web.service.SysPermissionService;
import com.bzkj.framework.web.service.TokenService;
import com.bzkj.system.domain.SysUserRole;
import com.bzkj.system.service.ISysDeptService;
import com.bzkj.system.service.ISysRoleService;
import com.bzkj.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 角色信息
 * 
 * @author ruoyi
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/list")
    @ApiOperation("查询接口")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    @LogC(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/export")
    @ApiOperation("导出excel")
    public AjaxResult export(HttpServletResponse response, SysRole role)
    {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
        return AjaxResult.success();
    }

    @LogC(title = "角色管理", businessType = BusinessType.EXPORTPDF)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/exportPdf")
    @ApiOperation("导出pdf")
    public AjaxResult exportPdf(HttpServletResponse response, SysRole role)
    {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelPDFUtil<SysRole> util = new ExcelPDFUtil<SysRole>(SysRole.class);
        return util.exportPDF(response, list, "角色数据","角色数据",getUsername(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),"全量");
    }

    @LogC(title = "角色管理", businessType = BusinessType.EXPORTCSV)
    @PreAuthorize("@ss.hasPermi('system:role:export')")
    @PostMapping("/exportCsv")
    @ApiOperation("导出csv")
    public AjaxResult exportCsv(HttpServletResponse response, SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        try {
            CsvExportUtils.exportToWeb(response, "角色管理.csv", list);
            return AjaxResult.error("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("导出失败");
        }
    }
    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @LogC(title = "角色管理", businessType = BusinessType.INSERT, pkFieldNames = "role_id",
            tableNames = "sys_role", content = "'角色名称：'+#role.roleName"
    )
    @PostMapping
    @ApiOperation("新增接口")
    public AjaxResult add(@Validated @RequestBody SysRole role)
    {
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @PutMapping
    @LogC(title = "角色管理", businessType = BusinessType.UPDATE,
            tableNames = "sys_role",pkFieldNames = "role_id",
            content = "'角色名称：'+#role.roleName")
    @ApiOperation("修改接口")
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());
        
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
            {
                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return success();
        }
        return error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @LogC(title = "角色数据权限", businessType = BusinessType.UPDATE,
            tableNames = "sys_role",pkFieldNames = "role_id",
            content = "'角色名称：'+#role.roleName")
    @PutMapping("/dataScope")
    @ApiOperation("数据权限修改接口")
    public AjaxResult dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @LogC(title = "角色状态", businessType = BusinessType.UPDATE,
            tableNames = "sys_role",pkFieldNames = "role_id",
            content = "'角色id：'+#role.roleId")
    @PutMapping("/changeStatus")
    @ApiOperation("状态修改接口")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @LogC(title = "角色管理", businessType = BusinessType.DELETE,content = "'角色id：'+#roleIds")
    @DeleteMapping("/{roleIds}")
    @ApiOperation("停用接口")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/allocatedList")
    @ApiOperation("分配用户列表查询接口")
    public TableDataInfo allocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @GetMapping("/authUser/unallocatedList")
    @ApiOperation("查询待分配角色用户列表接口")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }

    /**
     * 取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @LogC(title = "角色管理", businessType = BusinessType.UNGRANT,content = "'角色id：'+#userRole.roleId")
    @PutMapping("/authUser/cancel")
    @ApiOperation("取消授权")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @LogC(title = "角色管理", businessType = BusinessType.UNGRANT,content = "'角色id:'+#roleId+',取消授权用户id：'+#userIds")
    @PutMapping("/authUser/cancelAll")
    @ApiOperation("批量取消授权")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @LogC(title = "角色管理", businessType = BusinessType.GRANT,content = "'角色ID：'+#roleId+',用户id：'+#userIds")
    @PutMapping("/authUser/selectAll")
    @ApiOperation("批量授权接口")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        roleService.checkRoleDataScope(roleId);
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @GetMapping(value = "/deptTree/{roleId}")
    @ApiOperation("获取对应角色部门树列表接口")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return ajax;
    }
}
